package wh.coach.controller;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import wh.coach.domain.User2;
import wh.coach.domain.service.User2Service;
import wh.coach.web.controller.result.Result;

/**
 * @Author xhw
 * @Date 2023/9/26
 * @Version 1.0
 */
@RestController
@RequestMapping("/users2")
public class User2Controller {

    private final User2Service user2Service;

    private User2Controller(User2Service user2Service) {
        this.user2Service = user2Service;
    }

    // 添加用户
    @PostMapping("/")
    public Result<Long> addUser(@RequestBody User2 user2) {
        user2Service.addUser(user2);
        return Result.ok(user2.getUserId());
    }

    // 删除用户
    @DeleteMapping("/{userId}")
    public Result<Void> deleteUserById(@PathVariable("userId") Long userId) {
        user2Service.deleteUserById(userId);
        return Result.ok();
    }

    // 获取所有用户或根据名称搜索用户
    @GetMapping("/")
    public Result<List<User2>> getAllUsers(@RequestParam(value = "name", required = false) String searchName) {
        if (searchName == null) {
            List<User2> userList = user2Service.getAllUsers();
            return Result.ok(userList);
        } else {
            List<User2> userList = user2Service.findUsersBySearchName(searchName);
            return Result.ok(userList);
        }
    }

    // 根据用户ID获取用户信息
    @GetMapping("/{userId}")
    public Result<User2> getUserById(@PathVariable("userId") Long userId) throws JsonProcessingException {
        User2 user2 = user2Service.getUserById(userId);
        if (user2 != null) {
            return Result.ok(user2);
        } else {
            return Result.error("500", "该用户不存在");
        }
    }

    // 更新用户信息
    @PutMapping("/{userId}")
    public Result<Void> updateUser(@PathVariable("userId") Long userId, @RequestBody User2 user2) {
        user2.setUserId(userId);
        user2Service.updateUser(user2);
        int i = user2Service.updateUser(user2);

        return Result.ok();
    }

    // 更新用户信息（只更新名字）
    @PatchMapping("/{userId}")
    public Result<Void> updateUserName(@PathVariable("userId") Long userId, @RequestBody User2 user2) {
        user2.setUserId(userId);
        user2Service.updateUserName(user2);

        return Result.ok();
    }
}

